package com.icesoft.system.safe.service;

import com.icesoft.framework.core.exception.BusinessException;
import com.icesoft.system.safe.helper.RsaAesCryptoHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SafeRequestCryptoService {

	private static final ThreadLocal<String> signThreadLocal = new ThreadLocal<>();

	public String getSign() {
		String sign = signThreadLocal.get();
		assert sign != null;
		return sign;
	}

	public void decryptSign(String privateKey, String sign) {
		sign = RsaAesCryptoHelper.privateDecrypt(privateKey, sign);
		signThreadLocal.set(sign);
	}

	public String decryptReqBody(String body) throws BusinessException {
		String key = getSign();
		log.trace("key={}", key);
		if (key.length() != 16 && key.length() != 32) {
			log.info("密钥长度错误:{}", key);
			throw new BusinessException("密钥长度错误");
		}
		String params;
		try {
			params = RsaAesCryptoHelper.symmetricDecrypt(key, body);
		} catch (Exception e) {
			log.debug("解析出错，密文：{}", body);
			throw new BusinessException("数据解密出错，请检查加密数据是否正确");
		}
		return params;
	}

	public String encryptRespData(String data) {
		String sign = getSign();
		return RsaAesCryptoHelper.symmetricEncrypt(sign, data);
	}

	public void clearSign() {
		signThreadLocal.remove();
	}
}
